package han.bashe.web.servlet;

import han.bashe.business.ejb.LogQuery;
import han.bashe.common.entity.SoaConversation;
import han.bashe.common.entity.SoaErrorMessage;
import han.bashe.common.entity.SoaMessageExchange;
import han.bashe.common.entity.SoaRetryRecord;
import han.bashe.common.exception.BasheErrorCode;
import han.bashe.common.exception.BasheException;
import han.bashe.common.util.ExceptionUtils;

import java.io.IOException;
import java.util.List;

import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.xmlbeans.XmlObject;
import org.springframework.beans.BeanUtils;

import v1.log.bifang.han.LogQueryRequestDocument;
import v1.log.bifang.han.LogQueryResponseDocument;
import v1.log.bifang.han.ConversationDocument.Conversation;
import v1.log.bifang.han.MessageExchangeDocument.MessageExchange;
import v1.log.bifang.han.MessageExchangeDocument.MessageExchange.ErrorInfo;
import v1.log.bifang.han.RetryRecordDocument.RetryRecord;
import v1.log.bifang.han.RetryRecordDocument.RetryRecord.RetryData;
import v1.message.bashe.han.BasheErrorDocument;
import v1.message.bashe.han.BasheMessageDocument;
import v1.message.bashe.han.BasheErrorDocument.BasheError;

/**
 * Servlet implementation class for Servlet: NotifyServiceServlet
 * 
 */
public class LogQueryServlet extends javax.servlet.http.HttpServlet implements
		javax.servlet.Servlet {
	static final long serialVersionUID = 1L;

	@EJB
	private LogQuery query;

	public LogQueryServlet() {
		super();
	}

	/*
	 * (non-Java-doc)
	 * 
	 * @see javax.servlet.http.HttpServlet#doGet(HttpServletRequest request,
	 *      HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/*
	 * (non-Java-doc)
	 * 
	 * @see javax.servlet.http.HttpServlet#doPost(HttpServletRequest request,
	 *      HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		try {
			String xml = ServletReqResHeler.getRequestString(request);
			LogQueryRequestDocument doc = LogQueryRequestDocument.Factory
					.parse(xml);
			if (!doc.validate()) {
				throw new BasheException(BasheErrorCode.PARSE_CLIENT_XML_ERROR,
						"request xml is invalid");
			}
			LogQueryResponseDocument resDoc = LogQueryResponseDocument.Factory
					.newInstance();
			resDoc.addNewLogQueryResponse();
			if (doc.getLogQueryRequest().getViewConversationRequest() != null) {
				String id = doc.getLogQueryRequest()
						.getViewConversationRequest().getConId();
				SoaConversation con = query.getConversation(id);
				resDoc.getLogQueryResponse().addNewViewConversationResponse();
				if (con != null) {
					Conversation c = resDoc.getLogQueryResponse()
							.getViewConversationResponse().addNewConversation();
					BeanUtils.copyProperties(con, c);
				}

			} else if (doc.getLogQueryRequest().getViewMessageExchangeRequest() != null) {
				
				if (doc.getLogQueryRequest().getViewMessageExchangeRequest()
						.getMessageId() != null) {
					String mId = doc.getLogQueryRequest()
							.getViewMessageExchangeRequest().getMessageId();
					SoaMessageExchange sme = query.getMessageExchangeById(mId);
					MessageExchange me = resDoc.getLogQueryResponse()
							.addNewViewMessageExchangeResponse()
							.addNewMessageExchange();
					me.setId(mId);
					convert(sme, me);
				} else if (doc.getLogQueryRequest()
						.getViewMessageExchangeRequest().getRequestId() != null) {
					String rId = doc.getLogQueryRequest()
							.getViewMessageExchangeRequest().getRequestId();
					List<SoaMessageExchange> ls = query
							.getMessageExchangeByRequestId(rId);
					for (SoaMessageExchange sme : ls) {
						MessageExchange me = resDoc.getLogQueryResponse()
								.addNewViewMessageExchangeResponse()
								.addNewMessageExchange();
						me.setId(sme.getId());
						convert(sme, me);
					}
				}

			}
			
			System.out.println("####" + resDoc);
			ServletReqResHeler.setResponseString(response, resDoc.toString());
			
			
		} catch (BasheException e) {
			Log log = LogFactory.getLog(HttpServlet.class);
			log.error("LogQueryServlet.doPost() error", e);
			BasheErrorDocument error = BasheErrorDocument.Factory.newInstance();
			error.addNewBasheError();
			error.getBasheError().setErrorCode(e.getCode());
			error.getBasheError().setErrorMsg(e.getMsg());
			error.getBasheError().setErrorTrace(
					ExceptionUtils.getTraceAsString(e));
			ServletReqResHeler.setResponseString(response, error.toString());

		} catch (Exception e) {
			Log log = LogFactory.getLog(LogQueryServlet.class);
			log.error("LogQueryServlet.doPost() error", e);
			BasheErrorDocument error = BasheErrorDocument.Factory.newInstance();
			error.addNewBasheError();
			error.getBasheError().setErrorCode(BasheErrorCode.UNKNOWN_ERROR);
			error.getBasheError().setErrorMsg(e.getMessage());
			error.getBasheError().setErrorTrace(
					ExceptionUtils.getTraceAsString(e));
			ServletReqResHeler.setResponseString(response, error.toString());
		}
	}

	private void convert(SoaMessageExchange sme, MessageExchange me)
			throws Exception {

		me.addNewRequest();
		BasheMessageDocument reqDoc = BasheMessageDocument.Factory.parse(sme
				.getRequest().getMessage());
		
		me.getRequest().setBasheMessage(reqDoc.getBasheMessage());

		if (sme.getResponse() != null) {
			me.addNewResponse();
			BasheMessageDocument rdoc = BasheMessageDocument.Factory.parse(sme
					.getResponse().getMessage());
			me.getResponse().setBasheMessage(rdoc.getBasheMessage());
		}

		if (sme.getErrors() != null) {
			for (SoaErrorMessage e : sme.getErrors()) {
				ErrorInfo err = me.addNewErrorInfo();
				err.setErrorMsgId(e.getId());
				BasheError be = BasheError.Factory.newInstance();
				be.setErrorCode(e.getErrorCode());
				String tmp = "";
				if(e.getErrorMsg() != null)
					 tmp = e.getErrorMsg().replace("<", "&lt;");
				be.setErrorTrace(tmp);
				err.setBasheError(be);

			}
		}

		if (sme.getRetryRecords() != null) {
			for (SoaRetryRecord r : sme.getRetryRecords()) {
				RetryRecord rr = me.addNewRetryRecord();
				rr.setId(r.getId());
				rr.setErrorMsgId(r.getErrorMessageId());
				rr.setRetryTime(r.getRetryTime());
				rr.setStatus(r.getStatus());
				if (r.getRetryData() != null) {
					
					XmlObject xo = XmlObject.Factory.parse(r.getRetryData());
					
					rr.addNewRetryData().set(xo);
				}
			}
		}

	}
}